import {debounce} from '../utils'
function adjustColumnWidth(table) {
    if (table.$el) {
        table = table.$el
    }
    table.id = 'divTable'
    const colgroup = table.querySelector("colgroup");

    const colDefs = [...colgroup.querySelectorAll("col")];
    colDefs.forEach((col) => {
        const clsName = col.getAttribute("name");
        if (clsName === 'gutter') {
            return;
        }
        const cells = [
            ...table.querySelectorAll(`td.${clsName}`),
            ...table.querySelectorAll(`th.${clsName}`),
        ];
        // 忽略加了"leave-alone"类的列
        if (cells[0]?.classList?.contains?.("leave-alone")) {
            return;
        }
        const widthList = cells.map((el) => {
            return el.querySelector(".cell")?.scrollWidth || 0;
        });
        const max = Math.max(...widthList);
        const padding = 20;
        table.querySelectorAll(`col[name=${clsName}]`).forEach((el) => {
            el.setAttribute("width", max + padding);
        });
    });
    // 此段代码放入 adjustColumnWidth 内部最后面即可。
    const scrollingBody = table.querySelectorAll("div.is-scrolling-none");
    if (scrollingBody[0]?.classList?.contains?.("is-scrolling-none")) {
        scrollingBody[0].classList.remove("is-scrolling-none");
        scrollingBody[0].classList.add("is-scrolling-left");
        scrollingBody[0].style.overflowX = "auto";
    }
}
const tempFun = debounce(adjustColumnWidth, 200)

window.fit = tempFun

const divTable=(Table)=>{
    const mounted = Table.mounted;
        const resizeListener = Table.methods.resizeListener;
        Table.props.rowFit = {
            type: Boolean,
            default: false
        }
        Table.mounted = function () {
            mounted.apply(this, arguments)
            this.rowFit && window.fit(this)
        }
        Table.methods.resizeListener = function () {
            resizeListener.apply(this, arguments)
            this.rowFit && window.fit(this)
        }
}

export default {
    install(Vue, Table) {
        divTable(Table);
        Vue.directive('fit', {
            update() { },
            bind() { },
            inserted: tempFun,
            componentUpdated: tempFun,
            unbind() { },
        })
    }
}